package com.yinhe.music.yhmusic.main;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.PermissionChecker;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.umeng.message.inapp.IUmengInAppMsgCloseCallback;
import com.umeng.message.inapp.InAppMessageManager;
import com.yinhe.music.common.GlideHelper.GlideHelper;
import com.yinhe.music.common.popmenu.DropPopMenu;
import com.yinhe.music.common.popmenu.PopMenuItem;
import com.yinhe.music.common.view.RoundedImageView;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusNullObject;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.base.BaseActivity;
import com.yinhe.music.yhmusic.cache.CacheManager;
import com.yinhe.music.yhmusic.main.home.HomePageMusicFragment;
import com.yinhe.music.yhmusic.main.my.MyMusicFragment;
import com.yinhe.music.yhmusic.model.LangType;
import com.yinhe.music.yhmusic.model.Music;
import com.yinhe.music.yhmusic.personal.PersonActivity;
import com.yinhe.music.yhmusic.search.SearchActivity;
import com.yinhe.music.yhmusic.utils.MusicUtils;
import com.yinhe.music.yhmusic.utils.NetworkUtils;
import com.yinhe.music.yhmusic.utils.Preferences;
import com.yinhe.music.yhmusic.utils.SongUtil;
import com.yinhe.music.yhmusic.utils.ToastUtils;
import com.yinhe.music.yhmusic.utils.UpdateUtils;
import com.yinhe.music.yhmusic.utils.permission.Permissions;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.disposables.Disposable;


public class MainActivity extends BaseActivity implements ViewPager.OnPageChangeListener {

    @BindView(R.id.bar_my)
    TextView barmy;
    @BindView(R.id.bar_music)
    TextView barmusic;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.cancel)
    ImageView cancel;
    @BindView(R.id.net_tips)
    LinearLayout netTip;
    @BindView(R.id.main_viewpager)
    ViewPager mViewPager;
    @BindView(R.id.head_image)
    RoundedImageView headImage;

    private List<TextView> tabs = new ArrayList<>();
    private List<PopMenuItem> mMusicTypeList = new ArrayList<>();

    Disposable disposable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);
        ButterKnife.bind(this);
        RxBus.get().register(this);
        checkPermission();
        initView();

//        websocket
//        WsManager.getInstance().init();

        initMusicTypeListData();
        showQuickControl(true);
        disposable = UpdateUtils.checkUpdate(this, false);
        showTips();

        InAppMessageManager.getInstance(this).showCardMessage(this, "main",
                () -> {
                    //插屏消息关闭时，会回调该方法
                });
    }

    @Override
    protected void onDestroy() {
        RxBus.get().unregister(this);
        if (disposable != null) {
            disposable.dispose();
        }
        super.onDestroy();
    }

    /**
     * 显示音乐风格切换提示
     */
    private void showTips() {
        barmusic.postDelayed(() -> {
            if (Preferences.getIsFirst() && !MainActivity.this.isFinishing()) {
                showEducationPopMenu();
            }
        }, 1000);
    }

    private void showEducationPopMenu() {
        if (isFinishing()) {
            return;
        }
        if (CacheManager.getInstance().getNeedShowEducation()) {
            DropPopMenu dropPopMenu = new DropPopMenu(this);
            dropPopMenu.setTriangleIndicatorViewColor(Color.WHITE);
            dropPopMenu.setBackgroundResource(R.drawable.bg_drop_pop_menu_shap_blue);
            dropPopMenu.setItemTextColor(getResources().getColor(R.color.white));
            dropPopMenu.setTriangleIndicatorViewColor(Color.parseColor("#1D97FF"));
            List<PopMenuItem> list = new ArrayList<>();
            list.add(new PopMenuItem(0, "点击这里切换音乐类型"));
            dropPopMenu.setMenuList(list);
            dropPopMenu.show(barmusic, 30);
            Preferences.setIsFirst(false);
        }
    }

    /**
     * 设置首页头像
     */
    private void setHeadImage() {
        if (!Preferences.getLoginSn().isEmpty()) {
            setHeadImage(Preferences.getUserImage());
        } else {
            headImage.setImageResource(R.drawable.default_user_head);
        }

        headImage.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, PersonActivity.class);
            startActivity(intent);
        });
    }

    /**
     * 检查读写权限
     */
    private void checkPermission() {
        int permission = PermissionChecker.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        if (permission == PackageManager.PERMISSION_GRANTED) {
            new ScanTask().execute();
        } else {
            ToastUtils.show(getString(R.string.no_permission, Permissions.STORAGE_DESC, "扫描本地歌曲"));
            CacheManager.getInstance().setLoadingSuccess(true);
        }
    }

    /**
     * 初始化音乐风格列表
     */
    private void initMusicTypeListData() {
        mMusicTypeList.clear();

        List<LangType> list = CacheManager.getInstance().getMusicTypeList();
        for (LangType i : list) {
            mMusicTypeList.add(new PopMenuItem(R.drawable.ic_homepage_type_check,
                    i.typeid, i.typename));
        }
        barmusic.setText(mMusicTypeList.get(getSelectLangIndex()).itemTitle);
    }

    /**
     * 初始化界面
     */
    private void initView() {
        netTip.setVisibility(!NetworkUtils.isConnectInternet(this)
                ? View.VISIBLE
                : View.GONE);
        cancel.setOnClickListener(view -> netTip.setVisibility(View.GONE));

        setAppBar();
        setViewPager();
        setHeadImage();
    }

    private void setAppBar() {
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(false);
        }
        toolbar.setTitle("");
    }

    /**
     * 更新头像
     *
     * @param imgUrl 图片url
     */
    private void setHeadImage(String imgUrl) {
        GlideHelper.setCircleImageResource(headImage, imgUrl, R.drawable.default_user_head);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mService != null) {
            onChange(mService.getPlayingMusic());
        }
    }

    /**
     * 设置音乐馆和我的
     */
    private void setViewPager() {
        tabs.add(barmy);
        tabs.add(barmusic);

        CustomViewPagerAdapter customViewPagerAdapter = new CustomViewPagerAdapter(getSupportFragmentManager());

        customViewPagerAdapter.addFragment(MyMusicFragment.newInstance());
        customViewPagerAdapter.addFragment(HomePageMusicFragment.newInstance());
        mViewPager.setAdapter(customViewPagerAdapter);
        mViewPager.setOffscreenPageLimit(1);
        mViewPager.setCurrentItem(1);

        barmusic.setSelected(true);
        barmusic.setTextColor(getResources().getColor(R.color.tool_bar_text));

        mViewPager.addOnPageChangeListener(this);

        barmy.setOnClickListener(v -> mViewPager.setCurrentItem(0));

        barmusic.setOnClickListener((v) -> {
            if (mViewPager.getCurrentItem() == 1) {
                onClickPopWhite(barmusic);
                Drawable upArrow = getResources().getDrawable(R.drawable.ic_arrow_up);
                barmusic.setCompoundDrawablesWithIntrinsicBounds(null, null, upArrow, null);
            } else {
                mViewPager.setCurrentItem(1);
            }
        });
    }

    /**
     * 弹出音乐风格列表
     *
     * @param view 音乐馆
     */
    private void onClickPopWhite(View view) {
        CacheManager.getInstance().setShowEducation();
        final DropPopMenu dropPopMenu = new DropPopMenu(this);
        dropPopMenu.setTriangleIndicatorViewColor(Color.WHITE);
        dropPopMenu.setBackgroundResource(R.drawable.bg_drop_pop_menu_shap);
        dropPopMenu.setItemTextColor(getResources().getColor(R.color.c_3b3b3b));

        dropPopMenu.setOnItemClickListener((adapterView, v, position, id, popMenuItem) ->{
            if (dropPopMenu.getSelectIndex() != position) {
                CacheManager.getInstance().setTypeLangId(popMenuItem.itemId);
                barmusic.setText(popMenuItem.getItemTitle());
                RxBus.get().post(RxBusEventType.Home.CHANGE_LANG_TYPE, RxbusNullObject.INSTANCE);
            }
        });

        dropPopMenu.setOnDismissListener(() -> {
            Drawable downArrow = getResources().getDrawable(R.drawable.ic_arrow_down);
            barmusic.setCompoundDrawablesWithIntrinsicBounds(null, null, downArrow, null);
        });

        dropPopMenu.setMenuList(mMusicTypeList);
        dropPopMenu.setIsShowIcon(true);
        dropPopMenu.setSelectIndex(getSelectLangIndex());
        dropPopMenu.show(view, 30);
    }

    /**
     * 获取风格列表数目
     *
     * @return 类别个数
     */
    private int getSelectLangIndex() {
        int index = 0;
        for (PopMenuItem i : mMusicTypeList) {
            if (i.getItemId() == CacheManager.getInstance().getTypeLangId()) {
                return index;
            }
            index++;
        }
        return 0;
    }

    /**
     * 设置选中的tab
     *
     * @param position 位置
     */
    private void switchTabs(int position) {
        int index = 0;
        for (TextView i : tabs) {
            i.setSelected(position == index);
            index++;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        switchTabs(position);
        switch (position) {
            case 0:
                barmy.setTextColor(getResources().getColor(R.color.tool_bar_text));
                barmusic.setTextColor(getResources().getColor(R.color.unselect_bar_text));
                barmy.setTextSize(17);
                barmusic.setTextSize(15);
                break;
            case 1:
                barmy.setTextColor(getResources().getColor(R.color.unselect_bar_text));
                barmusic.setTextColor(getResources().getColor(R.color.tool_bar_text));
                barmy.setTextSize(15);
                barmusic.setTextSize(17);
                break;
            default:
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }


    private static class CustomViewPagerAdapter extends FragmentPagerAdapter {

        private final List<Fragment> mFragments = new ArrayList<>();

        CustomViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        void addFragment(Fragment fragment) {
            mFragments.add(fragment);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {

        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_search) {
            Intent intent = new Intent(MainActivity.this, SearchActivity.class);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_search, menu);
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    static class ScanTask extends AsyncTask<Void, Integer, List<Music>> {

        @Override
        protected List<Music> doInBackground(Void... voids) {
            return MusicUtils.scanMusic();
        }

        @Override
        protected void onPostExecute(List<Music> musicList) {
            CacheManager.getInstance().setLoadingSuccess(true);
            if (musicList != null) {
                CacheManager.getInstance().setScanMusic(musicList);
                RxBus.get().post(RxBusEventType.Music.SCAN_MUSIC, RxbusNullObject.INSTANCE);
                if (!musicList.isEmpty()) {
                    SongUtil.saveSong(musicList);
                }
            }
        }
    }


    /**
     * 登出回调
     *
     * @param rxbusNullObject 空Object
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.User.LOGOUT)

    )
    public void onRxbusLogoutEvent(RxbusNullObject rxbusNullObject) {
        headImage.setImageResource(R.drawable.default_user_head);
    }

    @Subscribe(tags = {
            @Tag(RxBusEventType.User.UPDATE_USER_INFO),
            @Tag(RxBusEventType.User.LOGIN_SUCCESS),
            @Tag(RxBusEventType.User.LOGIN_GET_USER)})
    public void onRxbusUpdateUser(RxbusNullObject rxbusNullObject) {
        setHeadImage();
    }

    /**
     * 网络状态改变
     *
     * @param isConnected 连接状态
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Home.NETWORK_CONNECT)
    )
    public void onRxbusNetworkStatusDidChanged(Boolean isConnected) {
        if (isConnected) {
            netTip.setVisibility(View.GONE);
        } else {
            netTip.setVisibility(View.VISIBLE);
        }
    }
}
